package org.example.device.sync;

import org.example.device.service.RealDeviceControlService;
import org.example.entity.Device;
import org.example.repository.DeviceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 设备状态同步服务
 * 定期同步设备状态，保持数据一致性
 */
@Service
public class DeviceStatusSyncService {
    
    @Autowired
    private RealDeviceControlService realDeviceControlService;
    
    @Autowired
    private DeviceRepository deviceRepository;
    
    /**
     * 定期同步所有设备状态
     * 每30秒执行一次
     */
    @Scheduled(fixedRate = 30000)
    public void syncAllDeviceStatus() {
        try {
            List<Device> devices = deviceRepository.findAll();
            System.out.println("开始同步设备状态，设备数量: " + devices.size());
            
            for (Device device : devices) {
                syncDeviceStatusAsync(device.getId());
            }
        } catch (Exception e) {
            System.err.println("设备状态同步失败: " + e.getMessage());
        }
    }
    
    /**
     * 异步同步单个设备状态
     */
    @Async
    public CompletableFuture<Void> syncDeviceStatusAsync(Long deviceId) {
        try {
            // 检查设备是否在线
            boolean isOnline = realDeviceControlService.isDeviceOnline(deviceId);
            
            // 获取设备状态
            Map<String, Object> status = realDeviceControlService.getDeviceStatus(deviceId);
            
            // 更新数据库中的设备状态
            Device device = deviceRepository.findById(deviceId).orElse(null);
            if (device != null) {
                device.setIsOnline(isOnline ? 1 : 0);
                
                // 如果获取到状态信息，更新设备属性
                if (status != null && !status.containsKey("error")) {
                    // 这里可以根据实际需要更新设备的其他属性
                    // 例如：device.setStatus((Integer) status.get("status"));
                }
                
                deviceRepository.save(device);
                System.out.println("设备 " + deviceId + " 状态同步完成，在线状态: " + isOnline);
            }
        } catch (Exception e) {
            System.err.println("设备 " + deviceId + " 状态同步失败: " + e.getMessage());
        }
        
        return CompletableFuture.completedFuture(null);
    }
    
    /**
     * 手动同步指定设备状态
     */
    public void syncDeviceStatus(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            // 检查设备连接
            boolean isOnline = realDeviceControlService.isDeviceOnline(deviceId);
            device.setIsOnline(isOnline ? 1 : 0);
            
            // 获取设备状态
            Map<String, Object> status = realDeviceControlService.getDeviceStatus(deviceId);
            if (status != null && !status.containsKey("error")) {
                // 根据状态信息更新设备属性
                if (status.containsKey("status")) {
                    device.setStatus((Integer) status.get("status"));
                }
            }
            
            deviceRepository.save(device);
            System.out.println("设备 " + deviceId + " 状态同步完成");
        } catch (Exception e) {
            System.err.println("设备 " + deviceId + " 状态同步失败: " + e.getMessage());
            throw new RuntimeException("设备状态同步失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量同步设备状态
     */
    public void syncDeviceStatusBatch(List<Long> deviceIds) {
        for (Long deviceId : deviceIds) {
            syncDeviceStatusAsync(deviceId);
        }
    }
    
    /**
     * 获取设备状态统计
     */
    public Map<String, Object> getDeviceStatusStats() {
        try {
            List<Device> devices = deviceRepository.findAll();
            
            long totalDevices = devices.size();
            long onlineDevices = devices.stream()
                .mapToLong(device -> device.getIsOnline())
                .sum();
            long offlineDevices = totalDevices - onlineDevices;
            
            return Map.of(
                "totalDevices", totalDevices,
                "onlineDevices", onlineDevices,
                "offlineDevices", offlineDevices,
                "onlineRate", totalDevices > 0 ? (double) onlineDevices / totalDevices : 0.0
            );
        } catch (Exception e) {
            System.err.println("获取设备状态统计失败: " + e.getMessage());
            return Map.of("error", "获取设备状态统计失败: " + e.getMessage());
        }
    }
}
